package gns

import (
	"context"
	"fmt"
	"net/http"
	"strings"
	"time"

	"gitee.com/liumou_site/logger"
	"github.com/spf13/cast"
)

// HttpStatus 检查给定主机的HTTP状态。
func (api *NetInfo) HttpStatus(host string) bool {
	var urls string
	if api.Port == 80 {
		urls = host
	} else {
		p := cast.ToString(api.Port)
		urls = host + ":" + p
	}
	if api.Https {
		urls = "https://" + urls
	} else {
		urls = "http://" + urls
	}
	mode := strings.ToUpper(api.Agreement)
	logger.Debug("Generate url", urls)
	logger.Debug("Usage mode", mode)
	return api.HttpStatusUrl(urls, time.Duration(api.Timeout)) == nil
}

// HttpStatusUrl 发送一个 HTTP GET 请求到指定的 URL，并检查响应状态码是否符合预期。
func (api *NetInfo) HttpStatusUrl(url string, timeout time.Duration) error {
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		logger.Error("Failed to create HTTP request: ", err)
		return err
	}
	req = req.WithContext(ctx)
	if api.Client == nil {
		api.Client = &http.Client{}
	}
	resp, err := api.Client.Do(req)
	if err != nil {
		logger.Error("Failed to send HTTP request: ", err)
		return err
	}
	defer func() {
		err = resp.Body.Close()
		if err != nil {
			logger.Error(err)
		}
	}()
	if resp.StatusCode != api.Code {
		logger.Error("Unexpected HTTP status code: ", resp.StatusCode)
		return fmt.Errorf("unexpected HTTP status code: %d", resp.StatusCode)
	}
	return nil
}
